package com.raspberry.nethelper.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Created by Tanck on 2/4/2017.
 * <p>
 * Describe:
 */

public class SocketHelper {

    private InputStream is;

    private OutputStream os;

    private Socket socket;

    public static SocketHelper instance;
    private PrintWriter pw;
    private SocketHelper() {
    }

    private SocketHelper(final String ip, final int port) {
        new Thread() {
            @Override
            public void run() {
                try {
                    socket = new Socket(ip, port);
                    is = socket.getInputStream();
                    os = socket.getOutputStream();
                    pw=new PrintWriter(os,true);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    public static SocketHelper getInstance(String ip, int port) {
        if (null == instance) {
            synchronized (SocketHelper.class) {
                if (null == instance)
                    instance = new SocketHelper(ip, port);
            }
        }
        return instance;
    }


    public InputStream getInputStream() {
        return is;
    }


    public OutputStream getOutputStream() {
        return os;
    }


    public void writeByte(final byte[] cmd) {
        new Thread() {
            @Override
            public void run() {
                try {
                    if (null != socket && !socket.isClosed()) {
//                        os.write(cmd);
                        pw.println(cmd);
//                        os.flush();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }


    public void writeString(final String buffer) {

        new Thread() {
            @Override
            public void run() {
                try {
                    if (null != socket && !socket.isClosed()) {
//                        os.write(buffer.getBytes());
//                        os.flush();
                        pw.println(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public void close() {
        try {
            if (null != socket && !socket.isClosed()) {
                is.close();
                os.close();
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
